package pers.w.chaptertalk.ui.search;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.SearchView;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Objects;

import pers.w.chaptertalk.MainActivity;
import pers.w.chaptertalk.R;
import pers.w.chaptertalk.ShowAndAddBookActivity;
import pers.w.chaptertalk.funs.BookInfo;
import pers.w.chaptertalk.funs.Fun;
import pers.w.chaptertalk.funs.db.Tab_Book;
import pers.w.chaptertalk.ui.ListViewAdapter;

public class SearchFragment extends Fragment {

    private SearchViewModel searchViewModel;
    private SearchView sv_bookName;
    private View root;

    private ListView lv_result;
    private Spinner spinner_webNames;
    private MainActivity activity ;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        searchViewModel =
                new ViewModelProvider(this).get(SearchViewModel.class);
        root = inflater.inflate(R.layout.fragment_search, container, false);


        Resources res = root.getContext().getResources();
        //把arrays.xml中的网址读取，并设置viewModel里面的hash表数据，从而在model处理
        setSV_bookName();
        setLV_result();
        spinner_webNames = root.findViewById(R.id.spiner_webNames);


        HashMap<String, String> bookResources = new HashMap<>();
        String[] bookResources_name = res.getStringArray(R.array.book_sources_names);
        String[] bookResources_uri = res.getStringArray(R.array.book_sources_uris);
        for (int i = 0; i < bookResources_name.length; i++) {
            bookResources.put(bookResources_name[i], bookResources_uri[i]);
        }

        searchViewModel.setBookResources(bookResources);


        /*设置结果监视*/
        searchViewModel.getQuery().observe(getViewLifecycleOwner(), bookInfoLiveDat -> {
            fillListView(bookInfoLiveDat.getInfo());
            //sv_bookName.setEnabled(true);
        });
        activity = (MainActivity) getActivity();

        return root;
    }


    private void setLV_result() {
        lv_result = root.findViewById(R.id.lv_result);
        lv_result.setOnItemClickListener((parent, view, position, id) -> {
            Intent show_and_add_book = new Intent(root.getContext(), ShowAndAddBookActivity.class);

          if (Fun.isDebug()) Log.d("listview", "点击了item" + position);

            Fun.SHARE_MAP.put(R.string.SHARE_LISTITEM,view.getTag());

            startActivity(show_and_add_book);
        });
    }

    private void setSV_bookName() {
        sv_bookName = root.findViewById(R.id.sv_bookName);
        sv_bookName.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                if (Fun.isNetworkConnected(getContext())){
                    activity.showLoading();
                    activity.showMsg("正在搜寻...");
                    searchViewModel.searchBooks(spinner_webNames.getSelectedItem().toString(), query);
                    sv_bookName.clearFocus();
                    lv_result.setAdapter(null);
                }
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
    }

    private ListViewAdapter listAdapter=null;//ListView的适配器

    private void fillListView(ArrayList<BookInfo> info) {
        activity.hideLoading();
        if (info.size() > 0) {
            // Map<String, Object> listMap;
            //listMap = new HashMap<>();
            //listMap.putAll(book.getFieldMap());
            ArrayList<BookInfo> books_list = new ArrayList<>(info);
            if (listAdapter!=null){
                listAdapter.stopThreads();
                listAdapter=null;
            }
            listAdapter = new ListViewAdapter(getContext(), getActivity(), books_list);
            listAdapter.setButtonText("");
            listAdapter.startBmpThreads();
            lv_result.setAdapter(listAdapter);

        } else {
            AlertDialog msgBox = new AlertDialog.Builder(this.getActivity())
                    .setPositiveButton("本主宰知道了",null)
                    .create();
            if (null == searchViewModel.getException()) {
                msgBox.setMessage("该资源没有找到该书籍，请重试，或者换源");
            } else {
                msgBox.setMessage("该资源网搜索失败，可能网络不好，也可能服务器访问超时，请重试或者换资源。\n因为很多网站是国外服务器，也可以尝试配合VPN");
                searchViewModel.resetException();
            }
            msgBox.show();
        }
    }
}
